package com.base.web.auth.controller;

import com.base.web.auth.service.UserService;
import com.base.web.core.common.BaseConstant;
import com.base.web.core.common.JsonResult;
import com.base.web.core.util.EncryptUtil;
import com.base.web.core.util.UuidUtil;
import com.base.web.model.master.auth.User;
import com.base.web.model.master.auth.UserRole;
import com.github.pagehelper.PageInfo;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.*;

/**
 * Created with IntelliJ IDEA.
 * Description: 用户控制类
 *
 * @Author: rentie
 * @Date: 2018/7/10 14:45
 */
@RestController
@RequestMapping("/user")
public class UserController {

    private Logger logger = LoggerFactory.getLogger(UserController.class);

    @Autowired
    private UserService userService;

    @PostMapping("/add")
    public JsonResult save(User bean) {
        Integer count;
        bean.setId(UuidUtil.getUUID32());
        bean.setPassword(EncryptUtil.Md5(bean.getPassword(), BaseConstant.MD5_HASHITERATIONS, BaseConstant.MD5_SALT));
        try {
            count = userService.insertSelective(bean);
        } catch (Exception e) {
            logger.error("添加用户异常={}", e.getMessage());
            return JsonResult.fail("添加用户异常");
        }
        return JsonResult.success(count);
    }

    @PostMapping("/del")
    public JsonResult del(User bean) {
        Integer count;
        try {
            bean.setStatus(BaseConstant.DATA_STATUS_DELETE);
            count = userService.updateByPrimaryKeySelective(bean);
        } catch (Exception e) {
            logger.error("删除用户异常={}", e.getMessage());
            return JsonResult.fail("删除用户异常");
        }
        return JsonResult.success(count);
    }

    @PostMapping("/checkPass")
    public JsonResult checkPass(User bean) {
        User temp;
        //加密页面输入的原始密码，用于比较
        String enterPass = EncryptUtil.Md5(bean.getPassword(), BaseConstant.MD5_HASHITERATIONS, BaseConstant.MD5_SALT);
        try {
            temp = userService.selectByPrimaryKey(bean.getId());
            if (Objects.equals(enterPass, temp.getPassword())) {
                return JsonResult.success();
            }
        } catch (Exception e) {
            logger.error("检查用户原始密码异常={}", e.getMessage());
            return JsonResult.fail("检查用户原始密码异常");
        }
        return JsonResult.fail();
    }

    @PostMapping("/addCheckLoginName")
    public JsonResult addCheckLoginName(User bean) {
        User temp;
        try {
            temp = userService.selectOne(bean);
            if (temp != null) {
                return JsonResult.success();
            }
        } catch (Exception e) {
            logger.error("检查登录名异常={}", e.getMessage());
            return JsonResult.fail("检查登录名异常");
        }
        return JsonResult.fail();
    }

    @PostMapping("/editCheckLoginName")
    public JsonResult editCheckLoginName(User bean) {
        User temp;
        try {
            String id = bean.getId();
            bean.setId(null);
            temp = userService.selectOne(bean);
            if (temp != null && !Objects.equals(temp.getId(), id)) {
                return JsonResult.success();
            }
        } catch (Exception e) {
            logger.error("检查登录名异常={}", e.getMessage());
            return JsonResult.fail("检查登录名异常");
        }
        return JsonResult.fail();
    }

    @PostMapping("/update")
    public JsonResult update(User bean) {
        Integer count;
        try {
            count = userService.updateByPrimaryKeySelective(bean);
        } catch (Exception e) {
            logger.error("修改用户异常={}", e.getMessage());
            return JsonResult.fail("修改用户异常");
        }
        return JsonResult.success(count);
    }

    @PostMapping("/updatePass")
    public JsonResult updatePass(User bean) {
        Integer count;
        bean.setPassword(EncryptUtil.Md5(bean.getPassword(), BaseConstant.MD5_HASHITERATIONS, BaseConstant.MD5_SALT));
        try {
            count = userService.updateByPrimaryKeySelective(bean);
        } catch (Exception e) {
            logger.error("修改用户异常={}", e.getMessage());
            return JsonResult.fail("修改用户异常");
        }
        return JsonResult.success(count);
    }

    /**
     * 查询用户列表
     *
     * @param map page   当前页
     *            limit 每页个数
     * @return
     */
    @GetMapping("/list")
    public JsonResult list(@RequestParam Map<String, String> map) {
        PageInfo<User> list = null;
        try {
            list = userService.select(User.defaultCondition(), map);
        } catch (Exception e) {
            logger.error("查询用户异常={}", e.getMessage());
            return JsonResult.fail("查询用户异常");
        }
        return JsonResult.success(list.getList(), list.getTotal());
    }

    @PostMapping("/roleBinding")
    public JsonResult roleBind(@RequestParam("userId") String userId, @RequestParam("roleIds") String[] roleIds) {
        List<UserRole> list = new ArrayList<UserRole>();
        for (String s : roleIds) {
            list.add(new UserRole(userId, s));
        }
        try {
            userService.roleBinding(userId, list);
        } catch (Exception e) {
            logger.error("用户角色绑定异常={}", e.getMessage());
            return JsonResult.fail("用户角色绑定异常");
        }
        return JsonResult.success(1);
    }


}